//
//  CETransformVC.m
//  digitalCurrency
//
//  Created by 来迎宾 on 2019/4/4.
//  Copyright © 2019年 XinHuoKeJi. All rights reserved.
//

#import "CETransformVC.h"
#import "CETransformCell.h"
#import "CETransformBottomCell.h"
#import "WCQRCodeVC.h"
#import "MineNetManager.h"
#import "HomeNetManager.h"
#import "AccountSettingInfoModel.h"
#import "CECaptialSettingVC.h"
#import "CTQGCell.h"
#import "CTRechargeRecordModel.h"
#import "JHUIAlertView.h"

@interface CETransformVC ()

@property (nonatomic, strong) UITextField *amountTextField;
@property (nonatomic, strong) UITextField *addrTextField;
@property (nonatomic, strong) UIButton *scanbtn;

@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) UIButton *sectionHeader;
@property (nonatomic, strong) NSMutableArray *records;
@property (nonatomic, assign) NSInteger page;

@property (nonatomic, strong) UITextField *textField;
@property (nonatomic, strong) UITextField *codeTF;
@property (nonatomic, strong) JHUIAlertView *alertView;

@property (nonatomic, strong) AccountSettingInfoModel *accountInfo;

@property (nonatomic, strong) UIButton *codeBtn;
@property (nonatomic, strong) NSTimer *numberTimer;
@property (nonatomic, assign) NSInteger timeCount;

@end

@implementation CETransformVC

- (instancetype)init
{
    self = [super init];
    if (self) {
        _records = [NSMutableArray array];
        _page = 1;
    }
    return self;
}

- (void)viewDidDsappear:(BOOL)animated{
    [super viewDidDisappear:animated];
    
    [self.numberTimer invalidate];
    self.numberTimer = nil;
}
    
- (void)viewDidLoad {
    [super viewDidLoad];
    self.viewTitle.text = LocalizationKey(@"Withdraw");
    [self.navigationController setNavigationBarHidden:NO animated:NO];

    [self.view addSubview:self.tableView];
    self.tableView.separatorColor = [UIColor clearColor];
    [self.tableView registerClass:[CTQGCell class] forCellReuseIdentifier:@"qgcell"];
    
    [self setHeadView];
    
    [self headRefreshWithScrollerView:self.tableView];
    [self footRefreshWithScrollerView:self.tableView];
    
    NSDictionary *dic = @{@"pageNum":@(_page),@"pageSize":@"20",@"coinId":self.unit};

    [self getRechargeRecordList:dic];
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];
    self.tableView.frame = self.view.bounds;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self accountSettingData];
}

- (void)refreshHeaderAction {
    _page = 1;
   NSDictionary *dic = @{@"pageNum":@(_page),@"pageSize":@"20",@"coinId":self.unit};
    [self getRechargeRecordList:dic];
}
    
- (void)refreshFooterAction {
    _page++;
   NSDictionary *dic = @{@"pageNum":@(_page),@"pageSize":@"20",@"coinId":self.unit};
    [self getRechargeRecordList:dic];
}

- (void)setHeadView{
    
    self.tableView.tableHeaderView = self.headerView;
    
    UIView *topView = [[UIView alloc]init];
    [self.headerView addSubview:topView];
    [topView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(0);
        make.height.equalTo(146);
    }];
    topView.backgroundColor = tMainColor;
    
    UIView *bgView = [[UIView alloc]initWithFrame:CGRectMake(16, 20, kWindowW-32, 284)];
    [self.headerView addSubview:bgView];
    bgView.backgroundColor = [UIColor whiteColor];
    bgView.layer.cornerRadius = 6.0;
    bgView.layer.shadowColor = [UIColor colorWithHEX:@"6E6E6E"].CGColor;
    bgView.layer.shadowOffset = CGSizeMake(0, 0);
    bgView.layer.shadowOpacity = 0.21;
    
    UILabel *addrTitleLB = [[UILabel alloc]init];
    [bgView addSubview:addrTitleLB];
    [addrTitleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(14);
        make.top.equalTo(21);
    }];
    addrTitleLB.font = kFont(12);
    addrTitleLB.textColor = tThreeColor;
    addrTitleLB.text = LocalizationKey(@"收款地址");
        
    UIView *lineView = [[UIView alloc]init];
    [bgView addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(14);
        make.right.equalTo(-14);
        make.top.equalTo(78);
        make.height.equalTo(0.5);
    }];
    lineView.backgroundColor = tTableViewCellLine;
    
    self.addrTextField = [[UITextField alloc]init];
    [bgView addSubview:self.addrTextField];
    [self.addrTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(14);
        make.height.equalTo(40);
        make.right.equalTo(-60);
        make.bottom.equalTo(lineView);
    }];
    self.addrTextField.placeholder = LocalizationKey(@"请输入收款地址");
    self.addrTextField.font = kFont(13);
    
    self.scanbtn = [[UIButton alloc]init];
    [bgView addSubview:self.scanbtn];
    [self.scanbtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(-21);
        make.centerY.equalTo(self.addrTextField);
        make.width.height.equalTo(22);
    }];
    [self.scanbtn setImage:ImageName(@"saoyisao") forState:UIControlStateNormal];
    [self.scanbtn addTarget:self action:@selector(scanqrcode) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *moneyTitleLB = [[UILabel alloc]init];
    [bgView addSubview:moneyTitleLB];
    [moneyTitleLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(14);
        make.top.equalTo(lineView.mas_bottom).offset(21);
    }];
    moneyTitleLB.font = kFont(12);
    moneyTitleLB.textColor = tThreeColor;
    moneyTitleLB.text = LocalizationKey(@"提现金额");
    
    UILabel *lastMoneyLB = [[UILabel alloc]init];
    [bgView addSubview:lastMoneyLB];
    [lastMoneyLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(-14);
        make.top.equalTo(lineView.mas_bottom).offset(21);
    }];
    lastMoneyLB.font = kFont(12);
    lastMoneyLB.textColor = tMainColor;
    lastMoneyLB.text = [NSString stringWithFormat:@"%@:%.4f %@",LocalizationKey(@"Available balance"),[self.canusedBalance floatValue],self.coinName];
        
    UIView *lineView1 = [[UIView alloc]init];
    [bgView addSubview:lineView1];
    [lineView1 mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(14);
        make.right.equalTo(-14);
        make.top.equalTo(156);
        make.height.equalTo(0.5);
    }];
    lineView1.backgroundColor = tTableViewCellLine;
    
    self.amountTextField = [[UITextField alloc]init];
    [bgView addSubview:self.amountTextField];
    [self.amountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(14);
        make.height.equalTo(40);
        make.right.equalTo(-60);
        make.bottom.equalTo(lineView1);
    }];
    self.amountTextField.placeholder = LocalizationKey(@"请输入提现金额");
    self.amountTextField.font = kFont(13);
    
    UILabel *feeMoneyLB = [[UILabel alloc]init];
    [bgView addSubview:feeMoneyLB];
    [feeMoneyLB mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(0);
        make.top.equalTo(lineView1.mas_bottom).offset(25);
    }];
    feeMoneyLB.font = kFont(12);
    feeMoneyLB.textColor = [UIColor colorWithHEX:@"#A19F9F"];
    feeMoneyLB.text = [NSString stringWithFormat:@"%@:%@ %@",LocalizationKey(@"Transfer charge"),self.fee,self.coinName];
    
   UIButton *okBtn = [[UIButton alloc]init];
    [bgView addSubview:okBtn];
    [okBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(lineView1.mas_bottom).offset(59);
        make.centerX.equalTo(0);
        make.left.equalTo(14);
        make.right.equalTo(-14);
        make.height.equalTo(44);
    }];
    okBtn.backgroundColor = [UIColor colorWithHEX:maincolor];
    [okBtn setTitle:LocalizationKey(@"确定") forState:UIControlStateNormal];
    okBtn.layer.cornerRadius = 4.0;
    [okBtn addTarget:self action:@selector(submit) forControlEvents:UIControlEventTouchUpInside];
    
}

- (void)closeView {
    [self.alertView dismiss];
    [self.view endEditing:YES];
    self.textField.text = @"";
    self.codeTF.text = @"";
}
    
- (void)submit
{
    if ([self.accountInfo.fundsVerified integerValue] == 0) {
        [self.view makeToast:LocalizationKey(@"setMoneyPassword") duration:1.5 position:CSToastPositionCenter];
        CECaptialSettingVC *setvc = [[CECaptialSettingVC alloc] init];
        [self.navigationController pushViewController:setvc animated:YES];
    }
    else {
        JHUIAlertConfig *config = [[JHUIAlertConfig alloc] init];
        
        config.title.text  = LocalizationKey(@"pinputPwd");
        config.title.color = [UIColor colorWithHEX:maincolor];
        config.title.bottomPadding = 100;
        config.dismissWhenTapOut   = NO;
        config.contentViewWidth    = SCREEN_WIDTH*0.8;
        config.contentViewHeight   = 180+80;
        self.alertView = [[JHUIAlertView alloc] initWithConfig:config];
        
        
        
        __weak typeof(self)weakself = self;
        [self.alertView addCustomView:^(JHUIAlertView *alertView, CGRect contentViewRect, CGRect titleLabelRect, CGRect contentLabelRect) {
            
            UIButton *closebtn = [UIButton buttonWithType:UIButtonTypeCustom];
            closebtn.tintColor = [UIColor blackColor];
            [closebtn setImage:[UIImage imageNamed:@"loginClose"] forState:UIControlStateNormal];
            [closebtn addTarget:weakself action:@selector(closeView) forControlEvents:UIControlEventTouchUpInside];
            closebtn.frame = CGRectMake(contentViewRect.size.width-30, 10, 20, 20);
            [alertView.contentView addSubview:closebtn];
            
            UIView *textBgView = [[UIView alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(titleLabelRect)+24, contentViewRect.size.width-30, 44)];
            textBgView.backgroundColor = kColor(@"EAEAEA");
            [alertView.contentView addSubview:textBgView];
            textBgView.layer.cornerRadius = 5;
            textBgView.layer.masksToBounds = YES;
            
            UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(22, CGRectGetMaxY(titleLabelRect)+24, contentViewRect.size.width-44, 44)];
            textField.backgroundColor = [UIColor colorWithHEX:@"EAEAEA"];
            textField.layer.cornerRadius = 5;
            textField.secureTextEntry =YES;
            textField.placeholder = LocalizationKey(@"inputMoneyPassword");
            [alertView.contentView addSubview:textField];
            weakself.textField = textField;
            
            UIView *codeBgView = [[UIView alloc]initWithFrame:CGRectMake(15, CGRectGetMaxY(titleLabelRect)+88, contentViewRect.size.width-30, 44)];
            codeBgView.backgroundColor = kColor(@"EAEAEA");
            [alertView.contentView addSubview:codeBgView];
            codeBgView.layer.cornerRadius = 5;
            codeBgView.layer.masksToBounds = YES;
            
            UITextField *codeTF = [[UITextField alloc] initWithFrame:CGRectMake(22, CGRectGetMaxY(titleLabelRect)+88, contentViewRect.size.width-44-80, 44)];
            codeTF.backgroundColor = [UIColor colorWithHEX:@"EAEAEA"];
            codeTF.layer.cornerRadius = 5;
            codeTF.keyboardType = UIKeyboardTypeNumberPad;
            codeTF.placeholder = LocalizationKey(@"Please enter SMS verification code");
            [alertView.contentView addSubview:codeTF];
            weakself.codeTF = codeTF;
            
            weakself.codeBtn = [[UIButton alloc]initWithFrame:CGRectMake(contentViewRect.size.width-35-80, CGRectGetMaxY(titleLabelRect)+88, 80, 44)];
            weakself.codeBtn.backgroundColor = [UIColor colorWithHEX:@"EAEAEA"];
            weakself.codeBtn.layer.cornerRadius = 5;
            [alertView.contentView addSubview:weakself.codeBtn];
            [weakself.codeBtn setTitle:LocalizationKey(@"Get verification code") forState:UIControlStateNormal];
            [weakself.codeBtn setTitleColor:[UIColor colorWithHEX:maincolor] forState:UIControlStateNormal];
            weakself.codeBtn.titleLabel.font = kFont(13);
            [weakself.codeBtn addTarget:weakself action:@selector(codeBtnAct) forControlEvents:UIControlEventTouchUpInside];
            [weakself.codeBtn setContentHorizontalAlignment:UIControlContentHorizontalAlignmentRight];
            
            UIButton *button = [UIButton buttonWithType:UIButtonTypeSystem];
            button.frame = CGRectMake(15, CGRectGetMaxY(textField.frame)+88, contentViewRect.size.width-30, 44);
            button.titleLabel.font = [UIFont systemFontOfSize:16];
            [button setTitle:LocalizationKey(@"Confirm") forState:0];
            [button setTitleColor:[UIColor whiteColor] forState:0];
            button.layer.cornerRadius = 5;
            button.backgroundColor = [UIColor colorWithHEX:maincolor];
            [button addTarget:weakself action:@selector(submitAll) forControlEvents:1<<6];
            [alertView.contentView addSubview:button];
        }];
        
        [self.view addSubview:self.alertView];
    }
}

- (void)codeBtnAct{
  
    self.timeCount = 60;
    self.numberTimer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(numberTimerAct) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.numberTimer forMode:NSDefaultRunLoopMode];
    self.codeBtn.userInteractionEnabled = NO;
    
    [self getphonncode];
}

- (void)numberTimerAct{
    
    if (self.timeCount == 1) {
        [self.numberTimer invalidate];
        self.numberTimer = nil;
        
        [self.codeBtn setTitle:LocalizationKey(@"Get verification code") forState:UIControlStateNormal];
        self.codeBtn.userInteractionEnabled = YES;
        return;
    }
    
    self.timeCount -- ;
    [self.codeBtn setTitle:[NSString stringWithFormat:@"%.2lds",self.timeCount] forState:UIControlStateNormal];
}

//获取手机验证码
-(void)getphonncode {
     [MineNetManager resetMoneyPasswordCodeForCompleteHandle:^(id resPonseObj, int code) {
           [EasyShowLodingView hidenLoding];
           NSInteger codeint = [resPonseObj[@"code"] integerValue];
           if (code) {
               if (codeint == 0) {
               }
           }
     }];
}

- (void)submitAll {
    if (self.textField.text.length == 0) {
        return;
    }
    
    if (self.codeTF.text.length == 0) {
        return;
    }
    
    [self.alertView dismiss];
    [self.view endEditing:YES];
    
    NSString *addr  = self.addrTextField.text;
    NSString *amont = self.amountTextField.text;
    NSString *secret = self.textField.text;
    NSString *codeStr = self.codeTF.text;
    if ([addr length] <= 0) {
        [self.view makeToast:LocalizationKey(@"Please enter address") duration:1.5 position:CSToastPositionCenter];
        return;
    }
    if ([amont length] <= 0) {
        return;
    }
    
    //self.nextbtn.enabled = NO;

//    if ([amont floatValue] > [self.canusedBalance floatValue]) {
//        [self.view makeToast:LocalizationKey(@"") duration:1.5 position:CSToastPositionCenter];
//        return;
//    }
    
    __weak typeof(self)weakself = self;
    [EasyShowLodingView showLodingText:LocalizationKey(@"loading")];
    [MineNetManager mentionCoinApplyForUnit:self.unit withAddress:addr withAmount:amont withFee:self.fee withRemark:@"beizhu" withJyPassword:secret mobilecode:[YLUserInfo shareUserInfo].ID codeStr:codeStr CompleteHandle:^(id resPonseObj, int code) {
        //self.nextbtn.enabled = YES;
        weakself.textField.text = @"";
        weakself.codeTF.text = @"";
        [EasyShowLodingView hidenLoding];
        NSLog(@"resPonseObj:%@",resPonseObj);
        NSInteger codeInt = [resPonseObj[@"code"] integerValue];
        if (code) {
            if (codeInt == 0) {
                [weakself.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [weakself.navigationController popViewControllerAnimated:YES];
                });
            }
            else if (codeInt == -1000001 ){
                [ShowLoGinVC showLoginVc:self withTipMessage:resPonseObj[MESSAGE]];
            }
            else {
                [weakself.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            [weakself.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"noNetworkStatus" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

- (void)getRechargeRecordList:(NSDictionary *)dic {
    __weak typeof(self)weakself = self;
    [HomeNetManager getWithdrawLogsInfo:dic CompleteHandle:^(id resPonseObj, int code) {
        if (code) {
            NSInteger codeInt = [resPonseObj[@"code"] integerValue];
            NSArray *data = resPonseObj[@"data"][@"list"];
            if (codeInt == 0) {
                if (_page == 1) {
                    [weakself.records removeAllObjects];
                }
                else {
                    if (data.count == 0) {
                        weakself.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                    }
                    return ;
                }
                for (NSDictionary *sub in data) {
                    CTRechargeRecordModel *model = [CTRechargeRecordModel mj_objectWithKeyValues:sub];
                    [weakself.records addObject:model];
                }
                
                [weakself.tableView reloadData];
                
            }
            else {
                [weakself.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            [weakself.view makeToast:LocalizationKey(@"noNetworkStatus") duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}
    
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.records.count;
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    return 70;
}
    
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    return self.sectionHeader;
}
    
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 60;
}
    
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CTQGCell *cell = [CTQGCell createTableView:tableView];
    CTRechargeRecordModel *model = _records[indexPath.row];
    cell.createTime.text = model.createTime;
    cell.coinName.text   = model.address;
    cell.coinName.font = kFont(12);
    cell.coinNumber.text = [NSString stringWithFormat:@"-%@",[ToolUtil judgeStringForDecimalPlaces:[model.amount stringValue] point:4]];
        
        return cell;
    
}

    //MARK:--账号设置的状态信息获取
-(void)accountSettingData {
    
    __weak typeof(self)weakself = self;
    [MineNetManager accountSettingInfoForCompleteHandle:^(id resPonseObj, int code) {
        NSInteger rescode = [resPonseObj[@"code"] integerValue];
        if (code) {
            if (rescode == 0) {
                if ([[NSString stringWithFormat:@"%@",resPonseObj[@"data"][@"result"]] isEqualToString:@"0"]) {
                    self.accountInfo = [AccountSettingInfoModel mj_objectWithKeyValues:@{@"fundsVerified":@"0"}];
                }
                else{
                    self.accountInfo = [AccountSettingInfoModel mj_objectWithKeyValues:@{@"fundsVerified":@"1"}];
                }
            }
            else if (rescode == 4000){
                [weakself showLoginViewController];
            }
            else {
                [weakself.view makeToast:resPonseObj[MESSAGE] duration:1.5 position:CSToastPositionCenter];
            }
        }
        else {
            [weakself.view makeToast:[[ChangeLanguage bundle] localizedStringForKey:@"noNetworkStatus" value:nil table:@"English"] duration:1.5 position:CSToastPositionCenter];
        }
    }];
}

- (UIView *)headerView {
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 325)];
        _headerView.backgroundColor = [UIColor whiteColor];
    }
    
    return _headerView;
}
    
- (UIButton *)sectionHeader {
    if (!_sectionHeader) {
        _sectionHeader = [UIButton buttonWithType:UIButtonTypeSystem];
        _sectionHeader.backgroundColor = [UIColor whiteColor];
        [_sectionHeader setTitle:LocalizationKey(@"Withdrawal record") forState:UIControlStateNormal];
        [_sectionHeader setTitleColor:tThreeColor forState:UIControlStateNormal];
        _sectionHeader.titleLabel.font = kFont(14);
        _sectionHeader.frame = CGRectMake(0, 0, SCREEN_WIDTH, 60);
    }
    
    return _sectionHeader;
}
    
- (void)scanqrcode {
    WCQRCodeVC *vc = [[WCQRCodeVC alloc] init];
    vc.textField   = self.addrTextField;
    [self.navigationController pushViewController:vc animated:YES];
}

-(void)dealloc{
    self.numberTimer = nil;

    NSLog(@"%s",__func__);
}

@end
